package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private WebSocketServer webSocketServer;

    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //异常情况的处理（收货地址为空、超出配送范围、购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();

        List<ShoppingCart> list = shoppingCartMapper.list(ShoppingCart.builder().userId(userId).build());
        if (list == null || list.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //构造订单数据
        Orders order = Orders.builder().phone(addressBook.getPhone())
                .address(addressBook.getDetail())
                .consignee(addressBook.getConsignee())
                .number(String.valueOf(System.currentTimeMillis()))
                .userId(userId)
                .status(Orders.PENDING_PAYMENT)
                .payStatus(Orders.UN_PAID)
                .orderTime(LocalDateTime.now())
                .build();
        BeanUtils.copyProperties(ordersSubmitDTO, order);


        //向订单表插入1条数据
        orderMapper.insert(order);
        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = OrderDetail.builder()
                    .orderId(order.getId())
                    .build();
            BeanUtils.copyProperties(cart, orderDetail);

            orderDetailList.add(orderDetail);
        }
        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);
        //清理购物车中的数据
        shoppingCartMapper.deleteAll(userId);
        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
        return orderSubmitVO;

    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.cancel(orders);
    }

    @Override
    public PageResult<OrderVO> conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.conditionSearch(ordersPageQueryDTO);
        Page<OrderVO> voPage = new Page<>();
        for (Orders orders : page) {
            List<OrderDetail> byId = orderDetailMapper.getById(orders.getId());
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(byId);
            voPage.add(orderVO);
        }
        return new PageResult(voPage.getTotal(), voPage.getResult());

    }

    @Override
    public OrderStatisticsVO statistics() {
        Integer toBeConfirmedint = orderMapper.status2();
        Integer confirmedint = orderMapper.status3();
        Integer deliveryInProgressint = orderMapper.status4();
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmedint);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgressint);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmedint);

        return orderStatisticsVO;

    }

    @Override
    public void delivery(Long id) {
        orderMapper.delivery(id);

    }

    @Override
    public OrderVO details(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(orders.getUserId());

        return orderVO;
    }

    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.complete(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {

        orderMapper.rejection(ordersRejectionDTO);
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        orderMapper.confirm(ordersConfirmDTO);
    }

    @Override
    public void repetition(Long id) {
        Orders orders = orderMapper.getById(id);
        ShoppingCart shoppingCart = new ShoppingCart();
        Long userId = orders.getUserId();
        shoppingCart.setUserId(userId);
        shoppingCartMapper.deleteAll(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        List<OrderDetail> orderDetailList = orderDetailMapper.getById(id);
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart s = new ShoppingCart();
           BeanUtils.copyProperties(orderDetail,s);
            list.add(s);
        }

        for (ShoppingCart cart : list) {
            ShoppingCartDTO shoppingCartDTO = new ShoppingCartDTO();
           BeanUtils.copyProperties(cart,shoppingCartDTO);
            shoppingCartService.add(shoppingCartDTO);
        }

    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


}